import axios from 'axios'
import { Message } from 'element-ui'

axios.defaults.timeout = 150000

// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    const $config = config
    $config.data = JSON.stringify(config.data)
    $config.headers = {
      'Content-Type': 'application/json;charset=UTF-8',
      'Access-Control-Allow-Origin': '*'
    }
    return $config
  },
  error => Promise.reject(error)
)

axios.interceptors.response.use(
  (response) => {
    // const res = response.data
    return response
  },
  error => Promise.reject(error)
)

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then((response) => {
        resolve(response.data)
      }, (err) => {
        reject(err)
        Message({
          message: '请求超时!请稍后再试',
          type: 'error'
        })
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then((response) => {
        resolve(response.data)
      }, (err) => {
        reject(err)
        Message({
          message: '请求超时!请稍后再试',
          type: 'error'
        })
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put (url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then((response) => {
        resolve(response.data)
      }, (err) => {
        reject(err)
        Message({
          message: '请求超时!请稍后再试',
          type: 'error'
        })
      })
  })
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function del (url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.delete(url, { params })
      .then((response) => {
        resolve(response.data)
      }, (err) => {
        reject(err)
        Message({
          message: '请求超时!请稍后再试',
          type: 'error'
        })
      })
  })
}
